{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "5ccdee54-84c7-44a3-8643-713a21e4763c",
   "metadata": {},
   "source": [
    "Chapter 07\n",
    "# 利用一层列表生成式完成矩阵转置\n",
    "Book_1《编程不难》 | 鸢尾花书：从加减乘除到机器学习 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "624cacfd-65d9-4ef9-a1f4-670352b8cb76",
   "metadata": {},
   "outputs": [],
   "source": [
    "def transpose(matrix):\n",
    "    transposed = []\n",
    "    rows = len(matrix)\n",
    "    cols = len(matrix[0])\n",
    "\n",
    "    for j in range(cols):\n",
    "        transposed_row = [matrix[i][j] \n",
    "                          for i in range(rows)]\n",
    "        transposed.append(transposed_row)\n",
    "\n",
    "    return transposed"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "7d7a58e8-2897-491e-998c-56a07e4c426d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 示例用法\n",
    "A = [[1, 2, 3],\n",
    "     [4, 5, 6]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "dc3ff784-83d0-4c1a-b4cf-65e6d5afe3ec",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[[1, 4], [2, 5], [3, 6]]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 调用自定义函数\n",
    "B = transpose(A)\n",
    "B"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
